<template>
  <div class="edit-page-container">
    <!-- 面包屑导航 -->
    <!--    <Breadcrumb :items="breadcrumbItems" />-->

    <div class="content-container">
      <div class="page-title">
        <h3>{{ isEditMode ? '编辑数据' : '新增数据' }}</h3>
      </div>

      <!-- 表单卡片 -->
      <el-card class="form-card">
        <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="120px"
            class="edit-form"
        >
          <!-- 表单字段 -->
          <el-form-item label="moduleName" prop="title">
            <el-input v-model="formData.title" placeholder="请输入" />
          </el-form-item>

          <el-form-item label="moduleUrl" prop="route">
            <el-input v-model="formData.route" placeholder="请输入" />
          </el-form-item>
<!-- 
          <el-form-item label="moduleIcon" prop="icon">
            <el-input v-model="formData.icon" placeholder="请输入" />
          </el-form-item> -->

          <el-form-item label="parentId" prop="pid">
            <el-select-v2
                v-model="formData.pid"
                :options="options"
                :loading="loading"
                clearable
                placeholder="Select"
            />
<!--            <el-input v-model="" placeholder="请输入" />-->
          </el-form-item>

        </el-form>
        <el-form-item class="form-actions">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="saveData">保存</el-button>
        </el-form-item>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import Breadcrumb from "@/components/breadcrumb/index.vue";
import {ElMessage} from "element-plus";
import api from '@/api/Menu.ts'

const router = useRouter();
const route = useRoute();
// 表单引用
const formRef = ref(null);

const options = []
// 表单数据
const formData = ref({
  id:'',
  pid:'',
  moduleLevel:'',
  systemNo:'',
  isLeaf:'',
  fullIndex:'',
  icon:'',
  moduleOrder:'',
  title:'',
  moduleNotes:'',
  route:'',
  createUser:'',
  updateUser:'',
  createTime:'',
  updateTime:''
});
let loading =ref(false);
// 表单验证规则
const rules = reactive({
  // name: [
  //   { required: true, message: '请输入名称', trigger: 'blur' },
  //   { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  // ],
  // description: [
  //   { required: true, message: '请输入描述', trigger: 'blur' }
  // ],
  // status: [
  //   { required: true, message: '请选择状态', trigger: 'change' }
  // ],
  // category: [
  //   { required: true, message: '请选择分类', trigger: 'change' }
  // ],
  // date: [
  //   { required: true, message: '请选择日期', trigger: 'change' }
  // ]
});

// 面包屑数据
const breadcrumbItems = [
  { label: '首页', path: '/' },
  { label: '数据管理', path: '/data' },
  // { label: isEditMode ? '编辑数据' : '新增数据' }
];

// 判断是否为编辑模式
const isEditMode = ref("");

// 模拟获取数据
const fetchData = async () => {

  formData.value = JSON.parse(sessionStorage.getItem("menu"));
  // try {
  //   const params = {
  //     userId: route.params.id
  //   };
  //   const response = await api.selectAll(params);
  //   if (response.code == 200 ) { // 根据你的API设计调整
  //     formData.value = response.data.list[0];
  //     console.log(" formData.value+", formData.value,response.data.list)
  //   } else {
  //     // API返回了错误码
  //     throw new Error(response.message || '获取数据失败');
  //   }
  // } catch (error) {
  //   console.error('加载数据失败:', error);
  //   // 友好的错误提示
  //   ElMessage.error({
  //     message: error.message || '加载数据失败，请稍后重试',
  //     duration: 3000
  //   });
  //   // 重置数据防止显示旧数据
  //   formData.value = [];
  // } finally {
  //   loading.value = false;
  // }
};
// 模拟保存数据 const response = await api.selectAll(params);
const saveData = async () => {
  let response;
  // 表单验证
  formRef.value.validate(async valid => {
    if (valid) {
      if (isEditMode.value) {
        response = await api.update(formData.value );
      }else{
        response = await api.insert(formData.value );
      }
      // 显示成功消息
      ElMessage.success(isEditMode.value ? '数据更新成功' : '数据创建成功');
      // 返回列表页
      router.push('/MenuPage');
    }
  });
};

// 取消编辑
const cancelEdit = () => {
  router.push("/MenuPage");
};


const getAllMenu = async () => {
  loading.value = true;
  try {
    const response = await api.select({});
    for (const item of  response.list) {
      if( item.id == null  ){
        options.push({
          value: item.id,
          label:item.title
        })
      }
    }
    loading.value = false;
  } catch (error) {
    console.error('加载数据失败:', error);
  }
  if (route.params.id !=null ||route.params.id !=undefined ) {
    isEditMode.value = true;
    const id = route.params.id;
    fetchData(id);
  }else{
    isEditMode.value = false;
  }
};
// 初始化数据
onMounted(() => {
  getAllMenu();

});

// // 监听路由变化，更新面包屑
// watch(
//     () => route.params.id,
//     (newId) => {
//       console.log("newId",newId)
//       isEditMode.value = !!newId;
//       breadcrumbItems[2].label = isEditMode.value ? '编辑数据' : '新增数据';
//
//       if (isEditMode.value) {
//         fetchData(newId);
//       } else {
//         // 重置表单
//         Object.assign(formData, {
//           id: null,
//           name: '',
//           description: '',
//           status: 'active',
//           category: 'category_a',
//           date: null,
//           attachment: null,
//         });
//       }
//     }
// );
</script>

<style scoped>
.edit-page-container {
  padding: 20px;
}

.content-container {
  margin-top: 20px;
}

.page-title {
  margin-bottom: 20px;
}
:deep( .el-card__body ){
  min-height: 61vh;
}
.form-card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}
.el-form-item {
  align-items: center;
}
.edit-form {
  width: 50%;
  margin: 53px auto;
}

.form-actions {
  margin-top: 30px;
  text-align: right;
}
.upload-btn {
  display: inline-block;
  vertical-align: middle;
}
:deep(.el-form-item__content) {
  justify-content: center !important;
}
.uploaded-file {
  margin-left: 10px;
  display: inline-block;
  vertical-align: middle;
}
</style>
